package com.et.protocol.core;

import androidx.annotation.NonNull;

public final class ByteUtil {
    private static final char[] HEX = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
    private static final StringBuilder log = new StringBuilder(512);
    private static final StringBuilder buff = new StringBuilder(256);

    synchronized static String toLog(@NonNull byte[] bs) {
        log.delete(0, log.length());
        for (byte b : bs) {
            log.append(HEX[(b >> 4) & 0xF]).append(HEX[b & 0xF]);
        }
        if (log.length() == 0) return "#";
        return log.toString();
    }

    static String toHex(@NonNull byte[] bs, int off, int len) {
        char[] c = new char[len << 1];
        byte b;
        for (int i = 0; i < len; i++) {
            b = bs[off + i];
            c[i << 1] = HEX[b >> 4 & 0xf];
            c[1 + (i << 1)] = HEX[b & 0xf];
        }
        return new String(c);
    }

    static boolean isOk(byte[] bs, int start, int len) {
        byte sum = 0;
        for (int i = 0; i < len - 1; i++) {
            sum += bs[i + start];
        }
        return sum == bs[start + len - 1];
    }

    static byte sum(byte[] bs, int start, int len) {
        byte sum = 0;
        for (int i = 0; i < len; i++) {
            sum += bs[i + start];
        }
        return sum;
    }

}
